package org.studiox.graph.runtime.service;

import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DB;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.studiox.graph.runtime.config.RuntimeConfig;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
public class MariaDBService {

  private static final Logger LOGGER = LoggerFactory.getLogger(MariaDBService.class);

  @Autowired private RuntimeConfig runtimeConfig;

  private DB db;

  @PostConstruct
  public void init() {
    if (runtimeConfig.isDatabaseEmbeddedEnabled()) {
      DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder();
      config.setPort(runtimeConfig.getDatabaseEmbeddedPort());
      config.setDeletingTemporaryBaseAndDataDirsOnShutdown(true);
      try {
        db = DB.newEmbeddedDB(config.build());
        db.start();
        db.source(
            runtimeConfig.getDatabaseEmbeddedFile(), runtimeConfig.getDatabaseEmbeddedSchema());
      } catch (ManagedProcessException e) {
        LOGGER.error(e.getMessage(), e);
      }
    }
  }

  @PreDestroy
  public void clean() {
    if (null != db) {
      try {
        db.stop();
      } catch (ManagedProcessException e) {
        LOGGER.error(e.getMessage(), e);
      }
    }
  }
}
